package ruifeng.zcj.dig.ui.shopping.order;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ruifeng.zcj.dig.R;
import ruifeng.zcj.dig.base.MyApp;
import ruifeng.zcj.dig.base.api.OSChinaApi;
import ruifeng.zcj.dig.groble.Constant;
import ruifeng.zcj.dig.groble.FragmentArgs;
import ruifeng.zcj.dig.groble.ToActivityUtil;
import ruifeng.zcj.dig.ui.selectcity.SelectCityActivity;
import ruifeng.zcj.dig.ui.selectcity.bean.City;
import ruifeng.zcj.dig.ui.shopping.bean.OrderResult;
import ruifeng.zcj.mybase.base.utils2.AbJsonUtil;
import ruifeng.zcj.mybase.base.utils2.StringUtils;
import ruifeng.zcj.pay.PayDemoActivity;

/**
 * Created by Administrator on 2016/10/11 0011.
 */
public class OrderAcitivity extends PayDemoActivity {
    protected String goodslist;// 订单信息
    protected double totalprice;// 商品总价格
    @Bind(R.id.activity_top_left)
    ImageView mActivityTopLeft;
    @Bind(R.id.activity_top_center)
    TextView mActivityTopCenter;
    @Bind(R.id.activity_top_right)
    ImageView mActivityTopRight;
    @Bind(R.id.activity_top_right_text)
    TextView mActivityTopRightText;
    @Bind(R.id.register_et_pwd)
    EditText mRegisterEtPwd;
    @Bind(R.id.register_et_rp_pwd)
    EditText mRegisterEtRpPwd;
    @Bind(R.id.order_address)
    TextView mOrderAddress;
    @Bind(R.id.order_address_layout)
    LinearLayout mOrderAddressLayout;
    @Bind(R.id.register_next)
    Button mRegisterNext;

    protected String ID;
    @Bind(R.id.detail_address)
    EditText mDetailAddress;
    private OrderResult mOrderResult;


    @Override
    public int getLayoutId() {
        return R.layout.activity_order;
    }

    @Override
    public void initView() {
        MyApp myApp = (MyApp) mApp;
        ID = myApp.getUserId();
        if (TextUtils.isEmpty(ID)) {
            ID = "6";
        }

        // goodslist",goodslist); // 所有订单信息
//        params.addBodyParameter("totalprice     商品总价

        Bundle bundle = getIntent().getExtras();
        FragmentArgs args = (FragmentArgs) bundle.getSerializable("goumainBundle");
        goodslist = (String) args.get("goodslist");
        totalprice = (double) args.get("totalprice");
    }


    @OnClick({R.id.order_address_layout, R.id.register_next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.order_address_layout:
                Intent intent0 = new Intent(this,
                        SelectCityActivity.class);
                startActivityForResult(intent0, Constant.SELECT_CITY_RESULT_CODE);

              //  ToActivityUtil.toNextActivity(this, SelectCityActivity.class);
                break;
            case R.id.register_next:// 确认订单
                if(check()){
                    requestData(false);
                }
                break;
        }
    }

    private boolean check() {
        if (TextUtils.isEmpty(mRegisterEtPwd.getText().toString().trim())){
            showSnackBar(""+getString(R.string.people_names_null) );
            return false;
        }
        if (!isMobileNo(mRegisterEtRpPwd.getText().toString().trim())){
            showSnackBar(""+getString(R.string.error_invalid_email));
            return false;
        }
        if (TextUtils.isEmpty(mOrderAddress.getText().toString().trim())){
            showSnackBar(""+getString(R.string.people_names_null));
            return false;
        }
        if (TextUtils.isEmpty(mDetailAddress.getText().toString().trim())){
            showSnackBar(""+getString(R.string.people_names_null));
            return false;
        }
        return true;
    }

    private boolean isMobileNo(String email) {
        //TODO: Replace this with your own logic
        return StringUtils.isMobileNo(email);
    }
    protected void requestData(boolean b) {

        /*
        (String totalprice, String userid,
                                   String goodslist,String consigneeaddress,
                                   String consigneearea,String consigneecity,
                                   String consigneeprovince,String consigneemobile,
                                   String consigneename,
        params.addBodyParameter("userid",userid);// 用户ID
        params.addBodyParameter("goodslist",goodslist); // 所有订单信息
        params.addBodyParameter("totalprice",totalprice); // 商品总价
        params.addBodyParameter("consigneeaddress",consigneeaddress);// 详细地址
        params.addBodyParameter("consigneearea",consigneearea);// 区
        params.addBodyParameter("consigneecity",consigneecity);// 市
        params.addBodyParameter("consigneeprovince",consigneeprovince);// 省
        params.addBodyParameter("consigneemobile",consigneemobile);// 收货人联系方式
        params.addBodyParameter("consigneename",consigneename);// 收货人姓名
        */
//        pay(null);
        OSChinaApi.submitorder("" + totalprice, ID, "" + goodslist, getDeatilAddress(), getConsigneearea(), consigneecity(), consigneeprovince(), phoneNumber(), getUserName(), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                showSnackBar("" + responseInfo.result);
                mOrderResult = (OrderResult) AbJsonUtil.fromJson(responseInfo.result, OrderResult.class);
                if (mOrderResult.OK()) {
                    pay(null);
                } else {
                    showSnackBar("提交订单失败，请重新提交");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                showSnackBar("提交订单失败，请重新提交");
            }
        });
    }

    //  详细地址
    protected String getDeatilAddress() {
        return "" + mDetailAddress.getText().toString().trim();
    }

    // 区
    protected String getConsigneearea() {
        return " ";
    }

    // 市
    protected String consigneecity() {
        return "市";
    }

    // 省
    protected String consigneeprovince() {
        return ""+mOrderAddress.getText().toString().trim();
    }

    // 联系电话
    protected String phoneNumber() {
        return "" + mRegisterEtRpPwd.getText().toString().trim();
    }

    // 用户名称
    protected String getUserName() {
        return "" + mRegisterEtPwd.getText().toString().trim();
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    protected String getOutTradeNo() {
        String key;
        if (mOrderResult != null) {
            showSnackBar("服务器产生的订单号码:"+mOrderResult.getOuttradno());
            return mOrderResult.getOuttradno();
        } else {
            SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
                    Locale.getDefault());
            Date date = new Date();
            key = format.format(date);

            Random r = new Random();
            key = key + r.nextInt();
            key = key.substring(0, 15);
        }
        return key;
    }

    protected String getNotifyUrld() {
        return "http://kw.runfkj.com/appservice/notifyurl.action";
    }

    /***
     * 商品名称
     **/
    protected String getShoppingName() {
        return " " + totalprice;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null || data.getExtras() == null)
            return;

        if (requestCode == Constant.SELECT_CITY_RESULT_CODE
                ) {
            if (data != null) {
                City city = (City) data.getExtras().get("city");
                City city2 = (City) data.getExtras().get("city2");

                StringBuffer append = new StringBuffer();
                if (city2 != null) {
                    append.append(city2.getArea_name());
                }
                if (city != null) {
                    append.append(city.getArea_name());
                    mOrderAddress.setText("" + append);
                }
            }
        }
    }

}
